import e, { Request, Response, Router, urlencoded, json } from 'express';

import * as todoService from '../services/todo.service.js'
import * as accountService from '../services/account.service.js'
import { Responses } from '../utils/responses.js'
import { randomInt } from 'node:crypto';
const router = Router();
//根据token，设置用户信息
router.use(async (req: Request, res: Response, next) => {
    //    //判断请求路径是否为 /account/register，/account/login，/account/logout
    //    const path = [
    //      'post /account/register',
    //      'post /account/login',
    //      'post /account/logout',
    //      'get /todos',
    //      'get /users',
    //      'get /'
    //    ]
    //    const regpath=[
    //      /\/todos\/\d/i,
    //      /\/users\/\d/i
    //    ]
    //    const test_path=`${req.method} ${req.path}`.toLocaleLowerCase()
    //    if(path.includes(req.path)){
    //      next()
    //      return
    //    }
    //    for (const reg of regpath) {
    //      if (reg.test(req.path)) {
    //        next()
    //        return
    //      }
    //    }


    const token = req.headers.authorization
    if (token) {
        const user = await accountService.getUserByToken(token)
        if (user) {
            req.body.user = user
        }
    }
    if (req.body.user) {
        next()
        return
    } else {
        res.status(401).send(Responses.error([], '未登录'));
        return
    }
})

//注销登录
router.post('/account/logout', async (req: Request, res: Response) => {
    try {
        await accountService.logout(req.body.user.id)
        res.send(Responses.success({}, '注销成功'));
    } catch (error) {
        res.status(400).send(Responses.error([], '注销异常'));
    }
})

// 账户路由
router.get('/account/', async (req: Request, res: Response) => {
    const userId = parseInt(req.body.user.id);
    const user = await accountService.getUserById(userId);
    if (user) {
        res.send(Responses.success(user, ''));
    } else {
        res.status(400).send(Responses.error([], '用户不存在'));
    }
});

//用户首页统计信息
router.get('/account/index', async (req: Request, res: Response) => {
    try {
        const userId = parseInt(req.body.user.id);
        let obj = await accountService.getUserTodoCount(userId)
        let messages_count = randomInt(5, 100)
        let messages_read_count= randomInt(1, messages_count)
        if (obj) {
            let data={
                todos_count:obj.total,
                todos_completed_count:obj.completed,
                messages_count,
                messages_read_count
            }

            res.send(Responses.success(data, ''));
        }else{
            res.status(400).send(Responses.error([], '用户不存在'));
        }
        //生成一个随机整数，用于测试
        // const random = Math.random()
        




    } catch (error) {
        res.status(400).send(Responses.error([],error.message));

    }
})
// 更新User信息
router.put('/account/', async (req: Request, res: Response) => {
    const userId = parseInt(req.body.user.id);
    const { username, password, description } = req.body;
    const user = await accountService.updateUser(userId, { userName: username, password: password, description: description })
    if (user) {
        const { password, ...rest } = user
        res.send(Responses.success(rest, '更新成功'));
    } else {
        res.status(400).send(Responses.error([], '更新失败'));
    }
})

// 创建新的 todo
router.post('/todos', async (req: Request, res: Response) => {
    try {
        let { title, description = '', completed } = req.body;
        if (completed == '') {
            completed = false
        }
        completed = !!parseInt(completed)
        const todo = await todoService.createTodo({ title, description, completed, user: req.body.user })
        res.send(Responses.success(todo, '创建成功'));
    } catch (error) {
        res.status(400).send(Responses.error([], error.message));
    }

});
//// 获取 当前登录用户todos 列表
router.get('/account/todos', async (req: Request, res: Response) => {
    //获取query参数
    try {
        const userId = parseInt(req.body.user.id);
        let { page = 1, title = '', completed = undefined } = req.query;
        let finished = undefined
        if (completed !== undefined) {
            finished = parseInt(completed as string)
            if (Number.isNaN(finished)) {
                finished = undefined
            }
        }
        if (page !== 1) {
            page = parseInt(page as string)
            if (Number.isNaN(page)) {
                page = 1
            }
        }
        if (title !== '') {
            title = title as string
        }
        const todos = await todoService.paginateTodos(userId, page, 3, title, finished);
        res.send(Responses.success(todos, ''));
    } catch (error) {
        res.status(400).send(Responses.error([], error.message));
    }
})

// 更新指定 id 的 todo
router.put('/todos/:id', async (req: Request, res: Response) => {
    try {
        let { id } = req.params;
        let { title, description, completed } = req.body;
        if (completed == '') {
            completed = false
        }
        completed = !!parseInt(completed)
        const todo = await todoService.updateTodo(parseInt(id), req.body.user.id, { title, description, completed })
        res.send(Responses.success(todo, '更新成功'));
    } catch (error) {
        res.status(400).send(Responses.error([], error.message));
    }
});

// 删除指定 id 的 todo
router.delete('/todos/:id', async (req: Request, res: Response) => {
    try {
        const { id } = req.params;
        let todo = await todoService.deleteTodo(parseInt(id), req.body.user.id)
        res.send(Responses.success(todo, '删除成功'));
    } catch (error) {
        res.status(400).send(Responses.error([], error.message));
    }
});


export default router;